package com.szc.demo01.controller;

import com.szc.demo01.config.FilePathProperties;
import com.szc.demo01.controller.base.BaseController;
import com.szc.demo01.exception.FieIsNotYoursException;
import com.szc.demo01.exception.NotBossException;
import com.szc.demo01.pojo.Emp;
import com.szc.demo01.pojo.MFile;
import com.szc.demo01.pojo.User;
import com.szc.demo01.service.EmpService;
import com.szc.demo01.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 文件管理控制器
 */
@Slf4j
@Controller
@EnableConfigurationProperties(FilePathProperties.class)
public class FormsController extends BaseController {

    @Resource
    EmpService empService;

    @Resource
    FilePathProperties filePathProperties;

    @Resource
    FileService fileService;



    @GetMapping("/form_layouts")
    public String formLayouts(Model model){
        List<Emp> list = empService.list();
        model.addAttribute("enamList",list);
        return "form/form_layouts";
    }

    /**
     * 上传文件
     * @param myFile 文件
     */
    @PostMapping("/upload")
    public String upload(@RequestPart("myFile") MultipartFile myFile,Long receiveId) throws IOException {

        MFile mFile = new MFile();
        //得到文件上传的内容
        //文件名
        String fName = myFile.getOriginalFilename();
        //发送者id
        long sendId = getUser().getId();
        //发送名
        String sendName = empService.getById(sendId).getEname();
        //接收id
        //接收名
        String receiveName = empService.getById(receiveId).getEname();
        //日期
        Date createTime = new Date();
        mFile.setFName(fName);
        mFile.setSendId(sendId);
        mFile.setSendName(sendName);
        mFile.setReceiveId(receiveId);
        mFile.setReceiveName(receiveName);
        mFile.setCreateTime(createTime);
        mFile.setIsAccept(0);

        //得到默认路径配置
        String basisPath = filePathProperties.getPath();
        String parentPath = basisPath + "document/";

        //创建父文件夹
        File parentFile=new File(parentPath);
        if(!parentFile.exists()){
            parentFile.mkdir();
        }

        //在父文件夹创建文件
        if (!myFile.isEmpty()) {
            File file = new File(parentPath + sendName);
            if (!file.exists()){
                file.mkdirs();
            }
            File file1 = new File(file, fName);
            FileUtils.copyInputStreamToFile(myFile.getInputStream(),file1);
        }
        String path =  parentPath + sendName + "/" + fName;
        mFile.setPath(path);

        fileService.save(mFile);
/*        if (otherImg.length!=0){
            for (MultipartFile multipartFile : otherImg) {
                String multipartFileName = multipartFile.getOriginalFilename();
                if (!multipartFile.isEmpty()){
                    File file2 = new File("D:/szcwork/" + username);
                    if (!file2.exists()){
                        file2.mkdirs();
                    }
                    File file3 = new File(file2, multipartFileName);
                    FileUtils.copyInputStreamToFile(headImg.getInputStream(),file3);
                }
            }
        }*/
        return "redirect:/beenSend.html";
    }

    /**
     * 已接收文件
     * @param model
     * @return
     */
    @GetMapping("/beenSend.html")
    public String beenSend(Model model){
        List<MFile> list = fileService.sendFiles(getUserId());
        model.addAttribute("files",list);
        return "form/form_send";
    }

    /**
     * 查找已发送文件
     * @param model
     * @return
     */
    @GetMapping("/receive.html")
    public String receive(Model model){
        List<MFile> list = fileService.receiveFiles(getUserId());
        model.addAttribute("files",list);
        return "form/form_receive";
    }

    /**
     * 查找未接收文件
     * @param model
     * @return
     */
    @GetMapping("/notreceive.html")
    public String notReceive(Model model){
        List<MFile> list = fileService.notreceiveFiles(getUser().getId());
        model.addAttribute("files",list);
        return "form/form_notreceive";
    }

    /**
     * 下载文件
     * @param fileId 文件id
     * @return
     */
    @GetMapping("/downLoadFile")
    public ResponseEntity<InputStreamResource> downLoadFile(@RequestParam("id") long fileId,
                                                            Model model)
            throws NotBossException, IOException {
        MFile mFile;
        if (userIdHasPerm(2)){
            mFile = fileService.getById(fileId);
        }else {
            mFile = fileService.downFile(fileId,getUser().getId());
        }
        String filePath;
        try {
            //如果报空指针异常则给全局异常处理（代表不是自己的文件）
            filePath = mFile.getPath();
        }catch (Exception e){
            throw new NotBossException("没有对应权限");
        }

        //文件设置为已读
        if (!userIdHasPerm(2)) {
            mFile.setIsAccept(1);
            fileService.updateById(mFile);
        }


        FileSystemResource file = new FileSystemResource(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}
